package com.aifast.common.util;

import cn.hutool.core.util.ObjectUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @Author fujian
 * @since 2022/1/13 10:34
 * 树形结构插件xmselect实体类
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class XmTree {

    private Integer value;
    private Integer pid;
    private String name;
    private Integer status;
    private Integer type;
    private List<XmTree> children = new ArrayList<>();
    private boolean disabled;

    private boolean optgroup;

    /**
     * 用于存放其他临时的值
     */
    private String tmpValue;

    public static List<XmTree> init(List<XmTree> list) {
        if (ObjectUtil.isNull(list) || list.size() == 0) {
            return Collections.emptyList();
        }
        List<XmTree> xmTrees = new ArrayList<>();
        list.stream().forEach(i -> {

            if (ObjectUtil.isNull(i.getPid()) || Objects.equals(0, i.getPid())
                    || Objects.equals("", i.getPid())) {
                xmTrees.add(i);
                return;
            }

            list.stream().forEach(j -> {
                if (Objects.equals(j.getValue(), i.getPid())) {
                    j.getChildren().add(i);
                    return;
                }
            });
        });
        return (xmTrees == null || xmTrees.size() == 0) ? list : xmTrees;
    }

}
